import 'base_model.dart';

class ChatRoom implements BaseModel {
  final int? id;
  final String name;
  final bool isGroup;
  final List<int> memberIds;
  final DateTime createdAt;
  final DateTime updatedAt;
  final String? lastMessage;
  final DateTime? lastMessageTime;

  ChatRoom({
    this.id,
    required this.name,
    required this.isGroup,
    required this.memberIds,
    required this.createdAt,
    required this.updatedAt,
    this.lastMessage,
    this.lastMessageTime,
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'is_group': isGroup ? 1 : 0,
      'member_ids': memberIds.join(','), // 将成员ID列表存储为逗号分隔的字符串
      'created_at': createdAt.millisecondsSinceEpoch,
      'updated_at': updatedAt.millisecondsSinceEpoch,
      'last_message': lastMessage,
      'last_message_time': lastMessageTime?.millisecondsSinceEpoch,
    };
  }

  factory ChatRoom.fromJson(Map<String, dynamic> json) {
    List<int> parseMemberIds() {
      if (json['member_ids'] == null) return [];
      return (json['member_ids'] as String)
          .split(',')
          .where((id) => id.isNotEmpty)
          .map((id) => int.parse(id))
          .toList();
    }

    return ChatRoom(
      id: json['id'],
      name: json['name'] ?? '',
      isGroup: json['is_group'] == 1,
      memberIds: parseMemberIds(),
      createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at']),
      updatedAt: DateTime.fromMillisecondsSinceEpoch(json['updated_at']),
      lastMessage: json['last_message'],
      lastMessageTime:
          json['last_message_time'] != null
              ? DateTime.fromMillisecondsSinceEpoch(json['last_message_time'])
              : null,
    );
  }

  // 复制对象并修改指定字段
  ChatRoom copyWith({
    int? id,
    String? name,
    bool? isGroup,
    List<int>? memberIds,
    DateTime? createdAt,
    DateTime? updatedAt,
    String? lastMessage,
    DateTime? lastMessageTime,
  }) {
    return ChatRoom(
      id: id ?? this.id,
      name: name ?? this.name,
      isGroup: isGroup ?? this.isGroup,
      memberIds: memberIds ?? this.memberIds,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      lastMessage: lastMessage ?? this.lastMessage,
      lastMessageTime: lastMessageTime ?? this.lastMessageTime,
    );
  }
}
